
const Dict = {};
const DictMapping = {};

const DictQueueCache = {};
const DictQueueEvent = async function (type) {
    return await commonInputProps.GetDict({ type });
};

async function GetDict(type) {
    if (type && Dict[type]) {
        return JSON.parse(JSON.stringify(Dict.type));
    } else if (type && !Dict[type]) {
        if (DictQueueCache[type]) {
            return DictQueueCache[type]
        } else {
            const _event = DictQueueEvent(type);
            DictQueueCache[type] = _event;
            try {
                const res = await _event;
                Dict[type] = res;
                delete DictQueueCache[type];
                return res;
            } catch (error) {
                delete DictQueueCache[type];
                throw error
            }
        }
    }
}

async function formatDictToMapping(options) {
    const type = options.type;
    const key = options.key || 'value';
    try {
        const res = await GetDict(type);
        const mapping = {};
        res.forEach(item => {
            mapping[item[key]] = item;
        });
        return mapping
    } catch (error) {
        console.error('格式化失败 =>', type, error)
    }
}

export default {
    install(app) {
        app.directive('dict', async (el, binding) => {
            const type = binding.arg;
            const options = binding.value;
            let value, valueKey, showKey;
            if (Array.isArray(options)) {
                value = options[0];
                valueKey = options[1] || 'value';
                showKey = options[2] || 'label';
            } else {
                value = options;
                valueKey = 'value';
                showKey = 'label';
            };
            let _Dict = DictMapping[`${type}_${valueKey}_${showKey}`]
            if (!_Dict) {
                _Dict = DictMapping[`${type}_${valueKey}_${showKey}`] = await formatDictToMapping({ type, key: valueKey })
            };
            const HtmlValue = _Dict[value][showKey];
            el.innerHTML = HtmlValue;
        })
    }
}


new Promise
